package pkg.orange.online;

import java.io.IOException;
import java.util.List;

import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Html;
//import android.util.Log;
import android.widget.RemoteViews;

import org.apache.http.client.ClientProtocolException;


/**
 * Usługa działająca w tle, która odpowiada za aktualizację widgeta.
 * Koniecznie usługa, bo aktualizacja ta może trwać nawet kilkadziesiąt sekund (serwery Orange...)
 *
 */
public class OrangeUpdateService extends IntentService {
	
	public OrangeUpdateService() {
		super("OrangeUpdateService");
	}

    @Override
    public void onHandleIntent(Intent intent) {
    	//pobieramy id widżetu
    	Bundle extras = intent.getExtras();
    	int appWidgetId=-1;
    	if(extras!=null)
    		appWidgetId = extras.getInt("appWidgetId",-1);

    	//Log.d("OrangeUpdateService", "onHandleIntent: poczatek, numer " + appWidgetId );
    	AppWidgetManager manager = AppWidgetManager.getInstance(this);
    	RemoteViews views = new RemoteViews(this.getPackageName(), R.layout.widget_layout);
    	
    	// Napis pobieranie...
    	views.setTextViewText(R.id.statusText, Html.fromHtml("<b>Pobieranie...</b>"));
        views.setTextColor(R.id.statusText, Color.WHITE); 
        manager.updateAppWidget(appWidgetId, views);
    	
       // Aktualizacja widgeta
       RemoteViews updateViews = buildUpdate(this, appWidgetId);
       
       //obsluga odswiezenia przez dotkniecie
	   Intent refreshIntent = new Intent(this, OrangeUpdateService.class);
	   refreshIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
	   PendingIntent pendingIntent = PendingIntent.getService(this,appWidgetId, refreshIntent,0);
	   updateViews.setOnClickPendingIntent(R.id.widgetContainer,pendingIntent);
       manager.updateAppWidget(appWidgetId, updateViews);
       //Log.d("OrangeUpdateService", "onHandleIntent: koniec");
       stopSelf();
    }
    
	//nie wykorzystujemy uslug zwiazanych - zwracamy null
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    public RemoteViews buildUpdate(Context context, int appWidgetId) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        //Ustawienia
        SharedPreferences config = context.getSharedPreferences(OrangeConfigureWidget.PREFS_NAME+Integer.toString(appWidgetId),0);
        //Tworzymy obiekt, który obsługuje konto Orange Online
    	OrangeHttpClient orangeClient = new OrangeHttpClient(config.getString("login", ""),config.getString("password", ""));
        String tmpFormName, tmpDisplayName;
    	for(int i=0; i<6; i++){
    		tmpFormName=config.getString("formName"+Integer.toString(i), "");
    		tmpDisplayName=config.getString("displayName"+Integer.toString(i), "");
    		if(tmpFormName.length()!=0 && tmpDisplayName.length()!=0)
    			orangeClient.addData(tmpFormName, tmpDisplayName);
        }
        
    	try {
			orangeClient.login("https://www.orange.pl/zaloguj.phtml?backUrl=/portal/ecare/packages");
			List<OrangeData> receivedData = orangeClient.fetchData();
			orangeClient.logout();
			//na widżecie jest miejsce na maksymalnie 6 pozycji
			//R.id.widgetText1;
			String htmlText="";
			boolean firstElement = true;
			for (OrangeData element : receivedData){
				element.debug();
				if(element.checkData()){
					if(firstElement){
						htmlText="<b>"+element.getDisplayName() +":</b> " + element.getFormattedValue();
						firstElement = false;
					}
					else
						htmlText=htmlText+"<br/><b>"+element.getDisplayName() +":</b> " + element.getFormattedValue();
				}
			}
			
			views.setTextViewText(R.id.widgetText,Html.fromHtml(htmlText));
			views.setTextColor(R.id.widgetText, Color.LTGRAY);
			views.setTextViewText(R.id.statusText,android.text.format.DateFormat.format("yyyy-MM-dd\nkk:mm:ss", new java.util.Date()));
			views.setTextColor(R.id.statusText, Color.GREEN);
    	} catch (OrangeLoginException e) {
			views.setTextViewText(R.id.statusText, Html.fromHtml("<b>Błąd\nlogowania</b>"));
			views.setTextColor(R.id.statusText, Color.RED);
			e.printStackTrace();
    	} catch (ClientProtocolException e) {
			views.setTextViewText(R.id.statusText, Html.fromHtml("<b>Błąd!!!</b>"));
			views.setTextColor(R.id.statusText, Color.RED);
			e.printStackTrace();
		} catch (IOException e) {
			views.setTextViewText(R.id.statusText, "Błąd!!!");
			views.setTextColor(R.id.statusText, Color.RED);
			e.printStackTrace();
		}
        
        return views;
    }



}
